package net.unix8.serial;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import com.ychmi.sdk.YcApi;

import android.util.Log;

public class NewSerialPort {
	private YcApi ycapi;
	private FileDescriptor fp;	
	private FileInputStream mInputStream;
	private FileOutputStream mOutputStream;
	public boolean isOpen=false;
	public FileInputStream getInputStream(){
		return mInputStream;
	}
	public NewSerialPort(String devNum, int speed, int dataBits, int stopBits,int parity){
		ycapi = new YcApi();
		fp = ycapi.openCom(ycapi.ttySAC1, speed,dataBits,0,stopBits); 
		if (fp == null) 
		{
			Log.e("NEW SERIAL PORT", "native open returns null");
			try 
			{
				throw new IOException();
			} catch (IOException e) {
				e.printStackTrace();
			}
			isOpen=false;
		}
		else
		{
			mInputStream = new FileInputStream(fp);
			mOutputStream = new FileOutputStream(fp);
			isOpen=true;
		}
	}
	public void closeSerial() {
		if (fp != null) {
			isOpen=false;
			ycapi.closeCom();	
			fp = null;
			mInputStream = null;
			mOutputStream = null;
		}
	}
	public boolean sendData(byte [] bytes) {
		try {
			 mOutputStream.write(bytes);
			 return true;
		} catch (Exception e) {
			return false;
		}
	}
	public boolean sendDataN(byte [] bytes, int len) {
		try {
			mOutputStream.write(bytes, 0, len);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
}
